/**
 * 用户全局状态
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { STORAGE_KEYS } from '@/config'
import { getStorage, setStorage, removeStorage } from '@/utils'
import type { UserInfo, LoginForm } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(getStorage(STORAGE_KEYS.TOKEN, true, null))
  const userInfo = ref<UserInfo | null>(getStorage(STORAGE_KEYS.USER_INFO, true, null))
  const loading = ref(false)
  const loginLoading = ref(false)
  const error = ref<Error | null>(null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value?.username || '')
  const nickname = computed(() => userInfo.value?.nickname || username.value)
  const avatar = computed(() => userInfo.value?.avatar || '')

  // 方法
  /**
   * 登录
   */
  const login = async (loginForm: LoginForm) => {
    loginLoading.value = true
    error.value = null

    try {
      // 实际项目中，这里应该调用登录API
      // 为了演示，使用模拟数据
      return new Promise<void>(resolve => {
        setTimeout(() => {
          const mockToken = 'mock_token_' + Date.now()
          const mockUserInfo: UserInfo = {
            id: 'user123456',
            username: loginForm.username,
            nickname: `用户${loginForm.username}`,
            avatar: 'https://placekitten.com/120/120',
            gender: 'male',
            createTime: Date.now(),
            updateTime: Date.now()
          }

          // 保存登录状态
          setToken(mockToken)
          setUserInfo(mockUserInfo)

          resolve()
        }, 1000)
      })
    } catch (err) {
      error.value = err as Error
      throw err
    } finally {
      loginLoading.value = false
    }
  }

  /**
   * 登出
   */
  const logout = () => {
    // 清除登录状态
    clearToken()
    clearUserInfo()

    // 实际项目中，可能还需要调用登出API
  }

  /**
   * 获取用户信息
   */
  const getUserInfo = async () => {
    if (!token.value) {
      throw new Error('未登录')
    }

    loading.value = true
    error.value = null

    try {
      // 实际项目中，这里应该调用获取用户信息API
      // 为了演示，使用模拟数据
      return new Promise<UserInfo>(resolve => {
        setTimeout(() => {
          if (userInfo.value) {
            resolve(userInfo.value)
          } else {
            const mockUserInfo: UserInfo = {
              id: 'user123456',
              username: 'tarouser',
              nickname: 'Taro用户',
              avatar: 'https://placekitten.com/120/120',
              gender: 'male',
              createTime: Date.now() - 86400000 * 30, // 30天前
              updateTime: Date.now()
            }

            // 保存用户信息
            setUserInfo(mockUserInfo)
            resolve(mockUserInfo)
          }
        }, 500)
      })
    } catch (err) {
      error.value = err as Error
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 设置Token
   */
  const setToken = (newToken: string) => {
    token.value = newToken
    setStorage(STORAGE_KEYS.TOKEN, newToken)
  }

  /**
   * 清除Token
   */
  const clearToken = () => {
    token.value = null
    removeStorage(STORAGE_KEYS.TOKEN)
  }

  /**
   * 设置用户信息
   */
  const setUserInfo = (newUserInfo: UserInfo) => {
    userInfo.value = newUserInfo
    setStorage(STORAGE_KEYS.USER_INFO, newUserInfo)
  }

  /**
   * 清除用户信息
   */
  const clearUserInfo = () => {
    userInfo.value = null
    removeStorage(STORAGE_KEYS.USER_INFO)
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    loginLoading,
    error,

    // 计算属性
    isLoggedIn,
    username,
    nickname,
    avatar,

    // 方法
    login,
    logout,
    getUserInfo,
    setToken,
    clearToken,
    setUserInfo,
    clearUserInfo
  }
})
